package org.nanhill.osgi.example.biz.impl;

import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanFactory {
	private ClassPathXmlApplicationContext ctx;

	public BeanFactory() {

		ctx = new BundleClassPathCtx(this.getClass().getClassLoader(),
				new String[] { "spring-persist.xml", "spring-manager.xml",
						"spring-biz.xml" });
		ctx.refresh();

	}

	@SuppressWarnings("unchecked")
	public <T> T getBean(Class<T> clz, String name) {
		return (T) ctx.getBean(name);
	}

	private class BundleClassPathCtx extends ClassPathXmlApplicationContext {
		private ClassLoader bundleClassLoader;

		public BundleClassPathCtx(ClassLoader bundleClassLoader,
				String[] configLocations) throws BeansException {
			super(configLocations, false);
			this.bundleClassLoader = bundleClassLoader;
		}

		@Override
		public void refresh() throws BeansException, IllegalStateException {
			ClassLoader old = Thread.currentThread().getContextClassLoader();
			Thread.currentThread().setContextClassLoader(bundleClassLoader);
			this.setClassLoader(bundleClassLoader);

			super.refresh();

			this.setClassLoader(old);
			Thread.currentThread().setContextClassLoader(old);
		}

	}

}
